#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>

std::timed_mutex mtx;
// try_lock_for(duration) —— 相对时间：从调用时刻开始算,最多等这么久。
// try_lock_until(time_point) —— 绝对时间：等到墙上的“那一刻”为止,不管调用早晚
void foo(int &num, int id)
{
    // 定义绝对时间
    auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(1);
    if (mtx.try_lock_until(deadline))
    {
        std::cout << "[Thread " << id << "] 抢到锁,开始干活 (Hold 1.2 s)\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(1200)); // ＞1 s
        ++num;
        mtx.unlock();
    }
    else
    {
        std::cout << "[Thread " << id << "] 抢到截止也没拿到锁,放弃\n";
    }
}

int main()
{
    int num = 1;
    std::thread t1(foo, std::ref(num), 1);
    std::thread t2(foo, std::ref(num), 2);

    t1.join();
    t2.join();

    std::cout << "final num = " << num << '\n';
    return 0;
}